<template>
  <div class="search-container">
    <!-- search顶部搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <searchResult :search-text="searchText" v-if="isResultShow"></searchResult>
    <!-- 联想建议 -->
    <searchSuggestion
      :search-text="searchText"
      v-else-if="searchText"
      @search="onSearch"
    ></searchSuggestion>
    <!-- 搜索历史记录 -->
    <searchHistory
      @clear-search-hitories="searchHistories = []"
      :search-histories="searchHistories"
      v-else
      @search="onSearch"
    ></searchHistory>
  </div>
</template>

<script>
import searchHistory from './component/search-history.vue'
import searchSuggestion from './component/search-suggestion.vue'
import searchResult from './component/search-result.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchText: '',
      isResultShow: false, // 控制搜索结果的显示与隐藏
      searchHistories: getItem('TOUTIAO-SEARCH_HISTORIES') || [] // 搜索的历史记录数据
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.searchText = val

      // 存储搜索历史纪录
      // 要求：不要有重复历史记录，最新的排在最前面
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel (val) {

    }
  },
  watch: {
    searchHistories (value) {
      setItem('TOUTIAO-SEARCH_HISTORIES', value)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
